﻿using System;
using System.Collections;
using System.Configuration;
using System.Data; 
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Microsoft.JCI.Common.Entity;
using System.Collections.Generic;
using Microsoft.JCI.Bll;
using Microsoft.JCI.Common.Utility;
using Microsoft.JCI.Portal.UserControl; 

namespace Microsoft.JCI.Portal.Dispatch
{
    public partial class AgentDispatchOrderAdd : BasePage
    {
        public Guid DispatchFormID
        {
            get
            {
                if (ViewState["DispatchFormID"] == null) return Guid.Empty;
                else return new Guid(ViewState["DispatchFormID"].ToString());
            }
            set
            {
                ViewState["DispatchFormID"] = value.ToString();
            }
        }

        public Guid CustomerID
        {
            get
            {
                if (ViewState["CustomerID"] == null) return Guid.Empty;
                else return new Guid(ViewState["CustomerID"].ToString());
            }
            set { ViewState["CustomerID"] = value.ToString(); }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
             if (!IsPostBack)
            {
                InitPage();

                if (Request.QueryString["CustomerID"] != null)
                {
                    CustomerID = new Guid(Request.QueryString["CustomerID"]);

                    ucCustomerCtrlInfo.CustomerID = CustomerID;

                      SystemBll bll = new SystemBll();
                      MadCustomerEntity tMadCustomerEntity = new MasterDataBll().Get<MadCustomerEntity>(CustomerID);
                      if (tMadCustomerEntity != null)
                      {
                          MasterDataBll mdBll = new MasterDataBll();
                          List<SysCompanyEntity> list = mdBll.GetCompanyListFromCacheByProvince(tMadCustomerEntity.Province);
                          ddlBranch.DataSource = list;
                          ddlBranch.DataTextField = "Name";
                          ddlBranch.DataValueField = "CompanyCode";
                          ddlBranch.DataBind();

                          if (rblSendTo.SelectedValue != "")
                          {
                              if (Convert.ToInt32(rblSendTo.SelectedValue) == (int)Enumerator.CompanyType.Vendor)
                              {
                                  LoadVendor();
                              }
                          }
                      }
                }

                if (Request.QueryString["DispatchFormID"] != null)
                {
                    DispatchFormID = new Guid(Request.QueryString["DispatchFormID"]);

                    LoadData();
                }

                if (CustomerID != Guid.Empty)
                {
                    GetDispatchHistory(CustomerID);
                }

                if (rblFormCategory.SelectedValue != string.Empty)
                {
                    LoadFormType(Convert.ToInt32(rblFormCategory.SelectedValue));
                }

                LoadBranch();
            }
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            ucCustomerCtrlInfo.OnProvinceSelectedIndexChanged +=new EventHandler<Telerik.WebControls.RadComboBoxSelectedIndexChangedEventArgs>(ucCustomerCtrlInfo_OnProvinceSelectedIndexChanged);
        }

        void ucCustomerCtrlInfo_OnProvinceSelectedIndexChanged(object sender, Telerik.WebControls.RadComboBoxSelectedIndexChangedEventArgs e)
        {
            LoadBranch();
        }

        private void InitPage()
        {
            EnumeratorHelper[] enums = EnumeratorHelper.GetFieldTexts(typeof(Enumerator.FormCategory));
            foreach (EnumeratorHelper e in enums)
            {
                rblFormCategory.Items.Add(new ListItem(e.EnumDisplayText, e.EnumValue.ToString()));
            }

            rblFormCategory.SelectedValue = ((int)Enumerator.FormCategory.Maintain).ToString();
 
            //用户控件
            SystemBll bll = new SystemBll();
            ddlM_IssueSource.DataSource = bll.GetDictionaryListFromCache(Microsoft.JCI.Common.Utility.Enumerator.DictionaryType.MaintainIssueSource);
            ddlM_IssueSource.DataTextField = "Value";
            ddlM_IssueSource.DataValueField = "DictionaryID";
            ddlM_IssueSource.DataBind();

            //ddlM_MaintainType.DataSource = bll.GetDictionaryListFromCache(Microsoft.JCI.Common.Utility.Enumerator.DictionaryType.MaintainType);
            //ddlM_MaintainType.DataTextField = "Value";
            //ddlM_MaintainType.DataValueField = "DictionaryID";
            //ddlM_MaintainType.DataBind();
            //ddlM_MaintainType.SelectedValue = "D5AF8409-93DF-4E91-97E2-404AF1D66232";


            pnlFormTypeMaintain.Visible = false;
            pnlFormTypeComplaint.Visible = false;
            pnlFormTypeAdvisory.Visible = false; 
        }

        private void LoadData()
        {
            if (DispatchFormID != Guid.Empty)
            {
                SystemBll bll = new SystemBll();
                DisDispatchFormEntity FormEntity = bll.Get<DisDispatchFormEntity>(DispatchFormID);
                if (FormEntity != null)
                {
                    //加载客户信息
                    ucCustomerCtrlInfo.CustomerID = FormEntity.CustomerId;
                    CustomerID = FormEntity.CustomerId;

                    //加载产品信息
                    ProductCtrl1.ProductID = FormEntity.ProductID;
                    ProductCtrl1.LoadProduct();

                    //加载派工单信息
                    rblFormCategory.SelectedValue = FormEntity.FormCategory.ToString();
                    if(FormEntity.M_IssueSource != Guid.Empty)
                        ddlM_IssueSource.SelectedValue = FormEntity.M_IssueSource.ToString();

                    ddlM_MaintainType.SelectedValue = FormEntity.M_MaintainType;

                    ddlM_Priority.SelectedValue = FormEntity.M_Priority;
                    txtM_PersonalityService.Text = FormEntity.M_PersonalityService;
                    txtM_HQappoint.Text = FormEntity.M_HQappoint;
                    txtM_RepairContent.Text = FormEntity.M_RepairContent;
                    txtM_Remark.Text = FormEntity.M_Remark;
                    txtComplaintDesc.Text = FormEntity.C_Description;
                    txtAdvisoryDesc.Text = FormEntity.A_Description;
                    RadDatePickerM_DiscoverDate.SelectedDate = FormEntity.M_DiscoverDate;

                    //根据客户所在区域加载办事处
                    if (FormEntity.AllocatedBranch != "" && FormEntity .AllocatedBranch != null)
                    {
                        MasterDataBll dataBll = new MasterDataBll();
                        SysCompanyEntity companyEntity = dataBll.GetCompanyFromCache(FormEntity.AllocatedBranch);
                        if (companyEntity != null && companyEntity.Province != "")
                        {
                            List<SysCompanyEntity> list = dataBll.GetCompanyListFromCacheByProvince(companyEntity.Province);
                            ddlBranch.DataSource = list;
                            ddlBranch.DataTextField = "Name";
                            ddlBranch.DataValueField = "CompanyCode";
                            ddlBranch.DataBind();
                        }

                        ddlBranch.SelectedValue = FormEntity.AllocatedBranch;
                    }
                }
             
          
            }
        }

        private void LoadFormType(int Type)
        {
            if (Type == (int)Enumerator.FormCategory.Maintain)
            {
                pnlFormTypeMaintain.Visible = true;
                pnlFormTypeComplaint.Visible = false ;
                pnlFormTypeAdvisory.Visible = false;
            }
            else if (Type == (int)Enumerator.FormCategory.Complaint)
            {
                pnlFormTypeMaintain.Visible = false;
                pnlFormTypeComplaint.Visible = true;
                pnlFormTypeAdvisory.Visible = false;
            }
            else if (Type == (int)Enumerator.FormCategory.Advisory)
            {
                pnlFormTypeMaintain.Visible = false;
                pnlFormTypeComplaint.Visible = false;
                pnlFormTypeAdvisory.Visible = true;
            }
        }

        private void GetDispatchHistory(Guid  customerID)
        {
            List<DisDispatchFormEntity> list = new DispatchBll().GetAll<DisDispatchFormEntity>(" and CustomerID = '"+customerID+"'");

            radgridFormHistoryList.DataSource = list;
            radgridFormHistoryList.DataBind();
        }

        protected void radgridFormHistoryList_ItemDataBound(object sender, Telerik.WebControls.GridItemEventArgs e)
        {
            if (e.Item.ItemType == Telerik.WebControls.GridItemType.Item || e.Item.ItemType == Telerik.WebControls.GridItemType.AlternatingItem)
            {
                LinkButton lnkbtnViewDispatch = e.Item.FindControl("lnkbtnViewDispatch") as LinkButton;
                if (lnkbtnViewDispatch != null)
                {
                    lnkbtnViewDispatch.Attributes.Add("onclick", "openMyFullWin('AgentDispatchOrderView.aspx?DispatchFormId=" + e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["DispatchFormId"].ToString() + "','GendDispatchOrderView');");
                }

                Label lblFormCategory = e.Item.FindControl("lblFormCategory") as Label;

                DisDispatchFormEntity entity = e.Item.DataItem as DisDispatchFormEntity;
                if (entity != null)
                {
                    lblFormCategory.Text = EnumeratorHelper.GetFieldText((Enumerator.FormCategory)entity.FormCategory);
                }

            }
        }

        protected void rblFormCategory_SelectedIndexChanged(object sender, EventArgs e)
        {
            LoadFormType(Convert.ToInt32(rblFormCategory.SelectedValue));
        }

        protected void lnkbtnComplete_Click(object sender, EventArgs e)
        {
            Save();
             DispatchBll bll = new DispatchBll();
            DisDispatchFormEntity entity =  bll.Get<DisDispatchFormEntity>(DispatchFormID);
            entity.FormStatus = (int)Enumerator.FormStatus.Closed;
            entity.AllocatedBranch = null;          
            bll.Update(entity);
            ClientScript.RegisterStartupScript(this.GetType(), "saveandclose", "window.close();", true);
        }

        private void Save()
        {
            DispatchBll bll = new DispatchBll();
            DisDispatchFormEntity entity = new DisDispatchFormEntity();
            //客户信息
            if (CustomerID == Guid.Empty)
            {
                CustomerID = Guid.NewGuid();

                ucCustomerCtrlInfo.CustomerID = CustomerID;

                bll.InsertOrUpdate(ucCustomerCtrlInfo.CustomerEntity);
            }
            else
            {
                ucCustomerCtrlInfo.CustomerID = CustomerID;

                bll.InsertOrUpdate(ucCustomerCtrlInfo.CustomerEntity);
            }

            //产品信息
            MadProductEntity mProductEntity = ProductCtrl1.GetEntity();
            if (mProductEntity != null)
            {
                mProductEntity.CustomerId = CustomerID;
                bll.InsertOrUpdate(mProductEntity);
            }

            //派单信息
            if (DispatchFormID != Guid.Empty)
            {
                entity = bll.Get<DisDispatchFormEntity>(DispatchFormID);
            }
            else
            {
                DispatchFormID = entity.DispatchFormId;
                entity.CreateBy = CurrentUserEntity.Account;
                entity.CreateOn = DateTime.Now;   
            }

            if (CustomerID != Guid.Empty)
            {
                entity.CustomerId = CustomerID;
            } 
            if (mProductEntity != null)
            {
                entity.ProductID = mProductEntity.ProductId;
            }
            entity.FormCode = bll.GetDispatchFormCode();
            entity.FormCategory = Convert.ToInt32(rblFormCategory.SelectedValue);
            entity.M_DiscoverDate = RadDatePickerM_DiscoverDate.SelectedDate.Value;
            if ( entity.FormCategory  == (int)Enumerator.FormCategory.Maintain)
            {
                if (ddlM_IssueSource.SelectedValue != string.Empty)
                    entity.M_IssueSource = new Guid(ddlM_IssueSource.SelectedValue);

                entity.M_MaintainType = ddlM_MaintainType.SelectedValue;

                entity.M_Priority = ddlM_Priority.SelectedValue;
                entity.M_PersonalityService = txtM_PersonalityService.Text;
                entity.M_HQappoint = txtM_HQappoint.Text;
                entity.M_RepairContent = txtM_RepairContent.Text;
                entity.M_Remark = txtM_Remark.Text;
            }
            else if (entity.FormCategory == (int)Enumerator.FormCategory.Complaint)
            {
                entity.C_Description = txtComplaintDesc.Text;
            }
            else if (entity.FormCategory == (int)Enumerator.FormCategory.Advisory)
            { entity.A_Description = txtAdvisoryDesc.Text; }

            //派工信息   
            if (rblSendTo.SelectedValue != "")
            {
                entity.AllocatedBranchDate = DateTime.Now;
                if (Convert.ToInt32(rblSendTo.SelectedValue) == (int)Enumerator.CompanyType.Branch)
                {
                    entity.AllocatedBranch = ddlBranch.SelectedValue; 

                }
                else if (Convert.ToInt32(rblSendTo.SelectedValue) == (int)Enumerator.CompanyType.Vendor)
                { 
                    entity.AllocatedVendor = ddlVendor.SelectedValue; 
                }

                entity.FormStatus = (int)Enumerator.FormStatus.Draft;
                entity.DispatchStatus = (int)Enumerator.DispatchStatus.None;   

            }
            else
            {
                entity.FormStatus = (int)Enumerator.FormStatus.Draft;
                entity.DispatchStatus = (int)Enumerator.DispatchStatus.None;   
            }

            bll.InsertOrUpdate(entity);
        }

        protected void lnkbtnSaveAndClose_Click(object sender, EventArgs e)
        {
            Save();
            ClientScript.RegisterStartupScript(this.GetType(), "saveandclose", "window.close();", true);
        }

        protected void lnkbtnSaveAndNew_Click(object sender, EventArgs e)
        {
            Save();
            DispatchFormID = Guid.NewGuid();
            ProductCtrl1.ProductID = Guid.NewGuid();
            RadDatePickerM_DiscoverDate.SelectedDate = null;
            if (Convert.ToInt32(rblFormCategory.SelectedValue) == (int)Enumerator.FormCategory.Maintain)
            {
                txtM_PersonalityService.Text = "";
                txtM_HQappoint.Text = "";
                txtM_RepairContent.Text = "";
                txtM_Remark.Text = "";
            }
            else if (Convert.ToInt32(rblFormCategory.SelectedValue) == (int)Enumerator.FormCategory.Complaint)
            { txtComplaintDesc.Text = ""; }
            else if (Convert.ToInt32(rblFormCategory.SelectedValue) == (int)Enumerator.FormCategory.Advisory)
            { txtAdvisoryDesc.Text = ""; }

            ClientScript.RegisterStartupScript(this.GetType(), "saveandnew", "alert('保存成功');", true);
        }

        private void LoadBranch()
        {
            if (ucCustomerCtrlInfo.ProvinceCode == "") return;
            if (rblSendTo.SelectedValue == "") return;
            MasterDataBll bll = new MasterDataBll();
            List<SysCompanyEntity> list = bll.GetCompanyListFromCacheByProvince(ucCustomerCtrlInfo.ProvinceCode);
            ddlBranch.DataSource = list;
            ddlBranch.DataTextField = "Name";
            ddlBranch.DataValueField = "CompanyCode";
            ddlBranch.DataBind();

            if (rblSendTo.SelectedValue != "")
            {
                if (Convert.ToInt32(rblSendTo.SelectedValue) == (int)Enumerator.CompanyType.Vendor)
                {
                    LoadVendor();
                }
            }
        }

        private void LoadVendor()
        {
            if (ddlBranch.SelectedValue == "") return;
            MasterDataBll bll = new MasterDataBll();
            List<SysCompanyEntity> list = bll.GetCompanyListFromCacheByParentCode(ddlBranch.SelectedValue);
            ddlVendor.DataSource = list;
            ddlVendor.DataTextField = "Name";
            ddlVendor.DataValueField = "CompanyCode";
            ddlVendor.DataBind();
        }

        protected void rblSendTo_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (rblSendTo.SelectedValue == "") return;

            if (Convert.ToInt32(rblSendTo.SelectedValue) == (int)Enumerator.CompanyType.Branch)
            {
                lblVendor.Visible = false;
                ddlVendor.Visible = false;
                LoadBranch();
            }
            else
            {
                lblVendor.Visible = true;
                ddlVendor.Visible = true;
                LoadVendor();
            }
        }

        protected void ddlBranch_SelectedIndexChanged(object sender, EventArgs e)
        {
            LoadVendor();
        }

        protected void lnkbtnDispatchAndClose_Click(object sender, EventArgs e)
        {
            DispatchBll bll = new DispatchBll();
            DisDispatchFormEntity entity = new DisDispatchFormEntity();
            //客户信息
            if (CustomerID == Guid.Empty)
            {
                CustomerID = Guid.NewGuid();

                ucCustomerCtrlInfo.CustomerID = CustomerID;

                bll.InsertOrUpdate(ucCustomerCtrlInfo.CustomerEntity);
            }

            //产品信息
            MadProductEntity mProductEntity = ProductCtrl1.GetEntity();
            if (mProductEntity != null)
            {
                mProductEntity.CustomerId = CustomerID;
                bll.InsertOrUpdate(mProductEntity);
            }

            //派单信息
            if (DispatchFormID != Guid.Empty)
            {
                entity = bll.Get<DisDispatchFormEntity>(DispatchFormID);
            }
            else
            {
                DispatchFormID = entity.DispatchFormId;
                entity.CreateBy = CurrentUserEntity.Account;
                entity.CreateOn = DateTime.Now;
            }

            if (CustomerID != Guid.Empty)
            {
                entity.CustomerId = CustomerID;
            }
            if (mProductEntity != null)
            {
                entity.ProductID = mProductEntity.ProductId;
            }
            entity.FormCode = bll.GetDispatchFormCode();
            entity.FormCategory = Convert.ToInt32(rblFormCategory.SelectedValue);
            if(RadDatePickerM_DiscoverDate.SelectedDate.HasValue)
            entity.M_DiscoverDate = RadDatePickerM_DiscoverDate.SelectedDate.Value;
            if (entity.FormCategory == (int)Enumerator.FormCategory.Maintain)
            {
                if (ddlM_IssueSource.SelectedValue != string.Empty)
                    entity.M_IssueSource = new Guid(ddlM_IssueSource.SelectedValue);

                entity.M_MaintainType = ddlM_MaintainType.SelectedValue;

                entity.M_Priority = ddlM_Priority.SelectedValue;
                entity.M_PersonalityService = txtM_PersonalityService.Text;
                entity.M_HQappoint = txtM_HQappoint.Text;
                entity.M_RepairContent = txtM_RepairContent.Text;
                entity.M_Remark = txtM_Remark.Text;
            }
            else if (entity.FormCategory == (int)Enumerator.FormCategory.Complaint)
            {
                entity.C_Description = txtComplaintDesc.Text;
            }
            else if (entity.FormCategory == (int)Enumerator.FormCategory.Advisory)
            { entity.A_Description = txtAdvisoryDesc.Text; }


            //派工信息
            if (rblSendTo.SelectedValue != "")
            {
                entity.AllocatedBranchDate = DateTime.Now;
                if (Convert.ToInt32(rblSendTo.SelectedValue) == (int)Enumerator.CompanyType.Branch)
                {
                    if (ddlBranch.SelectedValue == "")
                    {
                        ClientScript.RegisterStartupScript(this.GetType(), "error1", "alert('请选择派工对象！');", true);
                        return;
                    }
                    entity.AllocatedBranch = ddlBranch.SelectedValue;
                    entity.FormStatus = (int)Enumerator.FormStatus.Dispatched;
                    entity.DispatchStatus = (int)Enumerator.DispatchStatus.DispatchedBranch;

                }
                else if (Convert.ToInt32(rblSendTo.SelectedValue) == (int)Enumerator.CompanyType.Vendor)
                {
                    if (ddlVendor.SelectedValue == "")
                    {
                        ClientScript.RegisterStartupScript(this.GetType(), "error2", "alert('请选择派工对象！');", true);
                        return;
                    }
                    entity.AllocatedVendor = ddlVendor.SelectedValue;
                    entity.FormStatus = (int)Enumerator.FormStatus.Dispatched;
                    entity.DispatchStatus = (int)Enumerator.DispatchStatus.DispatchedVendor;
                }
                else
                {
                    ClientScript.RegisterStartupScript(this.GetType(), "error3", "alert('请选择派工对象！');", true);
                    return;
                }

            }
            else
            {
                ClientScript.RegisterStartupScript(this.GetType(), "error4", "alert('请选择派工类型！');", true);
                return;
            }
            bll.InsertOrUpdate(entity);

            //发送短信
            if (rblSendTo.SelectedValue != "")
            {
                List<SysUserEntity> ReceiverList = new List<SysUserEntity>();
                if (Convert.ToInt32(rblSendTo.SelectedValue) == (int)Enumerator.CompanyType.Branch)
                {
                    if (ddlBranch.SelectedValue != "")
                    {
                        List<SysUserEntity> TempList = bll.GetAll<SysUserEntity>(" and CompanyCode like '%"+ddlBranch.SelectedValue+"%'");
                        if (TempList != null)
                        {
                            ReceiverList.AddRange(TempList);
                        }
                    }

                }
                else if (Convert.ToInt32(rblSendTo.SelectedValue) == (int)Enumerator.CompanyType.Vendor)
                {
                    if (ddlVendor.SelectedValue == "")
                    {
                        List<SysUserEntity> TempList = bll.GetAll<SysUserEntity>(" and CompanyCode like '%" + ddlVendor.SelectedValue + "%'");
                        if (TempList != null)
                        {
                            ReceiverList.AddRange(TempList);
                        }
                    } 
                }
                foreach (SysUserEntity Receiver in ReceiverList)
                {
                    SmsOutGoingEntity SmsEnty = new SmsOutGoingEntity();
                    SmsEnty.PhoneNumber = Receiver.Account;
                    string content = "派单号:{0},{1},用户名:{2},客户性质:{3},用户电话:{4},详细地址:{5},产品品牌:{6},产品机型:{7},报修类型:{8},故障描述:{9}. 派单人(callcenter):{10}";

                    string ProductBrand = "";
                    if(mProductEntity != null)
                    {
                        if (mProductEntity.ProductBrand != Guid.Empty)
                        {
                            SysDictionaryEntity dictEntity = new SystemBll().GetDictionaryFromCache(mProductEntity.ProductBrand);
                            if (dictEntity != null)
                            {
                                ProductBrand = dictEntity.ValueCN;
                            }
                        }
                    }
                    SmsEnty.Content = string.Format(content,
                                                        entity.FormCode,
                                                        rblFormCategory.SelectedItem.Text,
                                                        ucCustomerCtrlInfo.CustomerEntity.Name,
                                                        ucCustomerCtrlInfo.CustomerEntity.CustomerAttribute,
                                                        ucCustomerCtrlInfo.CustomerEntity.Mobile,
                                                        ucCustomerCtrlInfo.CustomerEntity.Address,
                                                        ProductBrand,
                                                        ((TextBox)(ProductCtrl1.FindControl("txtProductType"))).Text.ToString(),
                                                        ddlM_MaintainType.SelectedItem.Text,
                                                        txtM_RepairContent.Text,
                                                        CurrentUserEntity.UserName);
                    SmsEnty.CreatedDate = DateTime.Now;
                    SmsEnty.DispatchId = entity.FormCode;
                    SmsEnty.IsSent = false;

                    bll.Insert(SmsEnty);
                }
            }

            ClientScript.RegisterStartupScript(this.GetType(), "success5", "window.close();", true);
        }

    }
}
